<template>
  <div id="violationView" class="list">
    <div class="breadcrumb">
			<Breadcrumb separator=">">
				<BreadcrumbItem to="">违章管理</BreadcrumbItem>
				<BreadcrumbItem to="/violation/view">违章视图</BreadcrumbItem>
			</Breadcrumb>
		</div>
    <TableSearch>
      <Form :label-width="80">
        <Row :gutter="16">
          <Col :md="8">
            <FormItem label="机构">
              <Select v-model="searchForm.orgIds" placeholder="请选择机构" clearable :multiple="true">
								<OrgTreeOption></OrgTreeOption>
							</Select>
            </FormItem>
          </Col>
          <Col :md="8">
            <FormItem label="司机">
              <DriverComplete v-model="searchForm.driverIds" clearable :multiple="true"></DriverComplete>
            </FormItem>
          </Col>
          <Col :md="8">
            <FormItem label="日期">
              <Button :class="{'ivu-btn-primary':twelveMonthActive}" @click="twelveMonthClick">最近12个月</Button>
              <DatePicker v-model="year" @on-change="searchYearChange" type="year" :options="yearOption" :clearable="false" placement="bottom-end" transfer placeholder="选择年" style="width:120px;"></DatePicker>
            </FormItem>
          </Col>
        </Row>
      </Form>
			<Button type="primary" class="search-btn" icon="search" @click="search" long>查询</Button>
		</TableSearch>

    <div class="main">
      <Card dis-hover>
        <div id="lineChart" style="height:240px;" v-show="datas.length"></div>
        <div v-show="!datas.length" style="text-align:center;">暂无数据</div>
      </Card>

      <Card dis-hover style="margin-top:15px;" v-show="datas.length">
        <div id="categoryChart" style="height:600px;"></div>
      </Card>
    </div>

  </div>
</template>

<script>
	import {mapState,mapActions} from 'vuex'
  import moment from 'moment'
  import EChart from '@/plugin/EChart'
  import lodash from 'lodash'

  export default {
    data(){
      return {
        twelveMonthActive:true,
        year:null,
        searchForm:{orgIds:[],driverIds:[]},
        submitForm:{},
        isLoading:false,

        lineChart:null,
        categoryChart:null,
        yearOption:{
          disabledDate:(d)=>{
            return d > moment().toDate();
          }
        }
      };
    },
    computed:{
      ...mapState('base',['userinfo']),
      ...mapState('violation/violationView',['datas']),
    },
    methods:{
      moment,
      ...mapActions('violation/violationView',['loadData']),
      twelveMonthClick(){
        this.twelveMonthActive = true;
        this.year = null;
      },
      searchYearChange(v){
        if (v){
          this.twelveMonthActive = false;
        }
      },
      async search(){
        this.submitForm = {...this.searchForm};
        if (this.year) {
          this.submitForm.dateType = this.year.getFullYear();
        }
        await this.loadData({...this.submitForm});
        if (this.datas.length) {
          this.createLineChart();
          this.createCategoryChart();
        }
      },
      createLineChart(){
        let dates = [...new Set(this.datas.map(o => o.date))];
        let series = dates.map(o => {
          let ds = this.datas.filter(v => v.date === o);
          let t = lodash.sumBy(ds,'wzCount');
          return t;
        });
        let option = {
          grid:{x:40,y:40,right:10,bottom:40},
          title:{text:'违章合计',x:'center',textStyle:{fontSize:16}},
          tooltip : {
            trigger: 'axis',
            formatter:(params)=>{
              let tooltiphtml = '';
              let xname = params[0].axisValue;
              tooltiphtml += `${xname}`;
              params.forEach(o => {
                tooltiphtml += `<br/><span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:${o.color};"></span>${o.seriesName}：${o.data}次`;
              });
              return tooltiphtml;
            }
          },
          // legend: { data:legend,show:false },
          xAxis:[{type: 'category',axisLabel:{interval:0},data: dates}],
          yAxis:[{type:'value',splitNumber:7,min:0},],
          series:[{name:'违章次数',type:'line',smooth:true,data:series}]
        };
        if (this.lineChart){
          this.lineChart.setOption(option);
        } else {
          this.lineChart = new EChart('lineChart',option);
        }
      },
      createCategoryChart(){
        let act = [...new Set(this.datas.map(o => o.act))];
        let seriesData = act.map(o => {
          let lst = this.datas.filter(v => v.act === o);
          let t = lodash.sumBy(lst,v => v.wzCount);
          return {name:o,value:t};
        });
        seriesData = lodash.sortBy(seriesData,['value']);
        act = seriesData.map(o => o.name);
        let option = {
          title:{show:false},
          grid:{x:200,y:10,right:40,bottom:30},
          tooltip : {
            trigger: 'axis',
            formatter:([item])=>{
              let tooltiphtml = `${item.data.name}<br/>违章：${item.value}次`;
              return tooltiphtml;
            }
          },
          yAxis:{type:'category',data:act},
          xAxis:{type:'value',splitNumber:7},
          series:[
            {
              name:'违章',type:'bar',barWidth:18,color:'#D181A0',
              label:{show:true,position:'right',color:'#333',formatter:'{c}次'},
              data:seriesData
            }
          ]
        };

        if (this.categoryChart){
          this.categoryChart.chart.off('click');
          this.categoryChart.setOption(option);
        } else {
          this.categoryChart = new EChart('categoryChart',option);
        }

        this.categoryChart.chart.on('click',(item)=>{
          let name = item.data.name;
          let curr = seriesData.forEach(o => {
            if (o.name === name) {
              o.itemStyle  = { color:'#FFCC00' };
            } else {
              o.itemStyle = null;
            }
          });
          this.categoryChart.chart.setOption(option);

          let curlist = this.datas.filter(o => o.act === name);
          let dates = curlist.map(o => o.date);
          let itemdata = curlist.map(o => o.wzCount);
          this.lineChart.options.xAxis[0].data = dates;
          this.lineChart.setTitle(name);
          this.lineChart.setSeriesData(0,itemdata);
        });
      }
    },
    mounted(){
      this.search();
    },
    destroyed(){
      this.lineChart && this.lineChart.dispose();
      this.categoryChart && this.categoryChart.dispose();
    }
  }
</script>
